import axios from 'axios'
import store from 'store'
import { Message } from 'element-ui'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 30000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.state.token) {
      config.headers.Authorization = 'Bearer ' + store.state.token
    }
    /* eslint-disable*/
    if (config.method === 'get' && config.params && config.params.hasOwnProperty('page')) {
      config.params = JSON.parse(JSON.stringify(config.params))
      config.params.page--
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  res => {
    return res.data
  },
  error => {
    const errorMsg = '操作失败请重试'
    if (!error.response) {
      Message.error(errorMsg)
      return Promise.reject()
    }
    const data = error.response.data || {}
    Message.error(data.title || errorMsg)
    return Promise.reject(error)
  }
)

export default service
